//
//  GeoData.m
//  GeoData
//
//  Created by zhenhua zhou on 12-7-7.
//  Copyright (c) 2012年 ECUST. All rights reserved.
//

#import "GeoData.h"
#import "SBJson.h"


@implementation GeoData

@synthesize CurRouteData,CurPosition, StartPosition, EndPosition, City, StartAddress, EndAddress;

-(GeoData *) init
{
    self = [super init];
    if(self)
    {
        CurRouteData = [[RouteData alloc] init];
        CurPosition = [[GeoPos alloc] init];
        StartPosition = [[GeoPos alloc] init];
        EndPosition = [[GeoPos alloc] init];
        City = [[NSString alloc] init];
        StartAddress = [[NSString alloc] init];
        EndAddress = [[NSString alloc] init];
    }
    
    return self;
}

- (void) dealloc
{
    if(CurRouteData)
    {
        [CurRouteData dealloc];
    }
    if(CurPosition)
    {
        [CurPosition dealloc];
    }
    if(StartPosition)
    {
        [StartPosition dealloc];
    }
    if(EndPosition)
    {
        [EndPosition dealloc];
    }
    
    if(City)
    {
        [City dealloc];
    }
    
    if(StartAddress)
    {
        [StartAddress dealloc];
    }
    
    if(EndAddress)
    {
        [EndAddress dealloc];
    }

    [super dealloc];
}

- (void) geoCurrentLocation
{
    //geo location from gps. POLLING SYNC
}
- (void) geoCity
{
    [self geoCurrentLocation];
    
    //send the location to server to get the city name. SYNC
}

- (void) parserDataWithString:(NSString *) str
{
    SBJsonParser * parser = [[[SBJsonParser alloc] init] autorelease];
    id jsonObj = [parser objectWithString:str];
    
    if(jsonObj==nil)
    {
        return;
    }
    
    if([jsonObj isKindOfClass:[NSDictionary class]])
    {
        NSDictionary * root = (NSDictionary *) jsonObj;
        if(root == nil)
        {
            return;
        }
        
        NSArray * routes = [ root objectForKey:@"routes"];//route here        
        if(routes == nil)
        {
            return;
        }
        assert([routes isKindOfClass:[NSArray class]]);
        
        for(NSDictionary * curRoute in routes)
        {
            assert([curRoute isKindOfClass:[NSDictionary class]]);
            
            NSArray *legs = [curRoute objectForKey:@"legs"];//segments;
            if(legs == nil)
                continue;
            assert([legs isKindOfClass:[NSArray class]]);
            
            double maxSegLat = 0;
            double maxSegLon = 0;
            double minSegLat = 0;
            double minSegLon = 0;
            Boolean isFirstSeg = true;
            
            for (NSDictionary *curleg in legs)
            {
                assert([curleg isKindOfClass:[NSDictionary class]]);
                
                Segment * seg = [[Segment alloc] init];
                
                
                NSArray * steps = [curleg objectForKey:@"steps"];//waypoints
                assert([steps isKindOfClass:[NSArray class]]);
                
                double maxWayPointLat = 0;
                double maxWayPointLon = 0;
                double minWayPointLat = 0;
                double minWayPointLon = 0;
                Boolean isFirstWaypoint = true;
                
                for( NSDictionary * curStep in steps)
                {                    
                    
                    
                    assert([curStep isKindOfClass:[NSDictionary class]]);
                    Waypoint * waypoint = [[Waypoint alloc] init];
                    if(waypoint)
                    {
                        NSDictionary * tmp = [curStep objectForKey:@"distance"];
                        if(tmp==nil)
                            break;
                        
                        waypoint.Distance = [tmp valueForKey:@"value"];
                        waypoint.DistanceStr = [tmp valueForKey:@"text"];
                        
                        tmp = [curStep objectForKey:@"duration"];
                        if(tmp!=nil)
                        {
                            waypoint.Duration = [tmp valueForKey:@"value"];
                            waypoint.DurationStr = [tmp valueForKey:@"text"];
                        }
                        
                        tmp = [curStep objectForKey:@"start_location"];
                        NSNumber * num = nil;
                        if(tmp!=nil)
                        {
                            num = [[NSNumber alloc] init];
                            num = [tmp valueForKey:@"lat"];
                            waypoint.StartPoint.Lat = [num doubleValue];
                            num = [tmp valueForKey:@"lng"];
                            waypoint.StartPoint.Lon = [num doubleValue];
                            
                            
                            //
                            maxWayPointLat = MAX(waypoint.StartPoint.Lat, maxWayPointLat);
                            maxWayPointLon = MAX(waypoint.StartPoint.Lon, maxWayPointLon);
                            
                            minWayPointLat = MIN(waypoint.StartPoint.Lat, minWayPointLat);
                            minWayPointLon = MIN(waypoint.StartPoint.Lon, minWayPointLon);
                            //update bounding box
                            
                        }
                        
                        tmp = [curStep objectForKey:@"end_location"];
                        if(tmp!=nil)
                        {                            
                            num = [[NSNumber alloc] init];
                            num = [tmp valueForKey:@"lat"];
                            waypoint.EndPoint.Lat = [num doubleValue];
                            num = [tmp valueForKey:@"lng"];
                            waypoint.EndPoint.Lon = [num doubleValue];
                            
                            //
                            maxWayPointLat = MAX(waypoint.EndPoint.Lat, maxWayPointLat);
                            maxWayPointLon = MAX(waypoint.EndPoint.Lon, maxWayPointLon);
                            
                            minWayPointLat = MIN(waypoint.EndPoint.Lat, minWayPointLat);
                            minWayPointLon = MIN(waypoint.EndPoint.Lon, minWayPointLon);
                            //update bounding box

                        }
                        
                        if(isFirstWaypoint)
                        {
                            maxWayPointLat = MAX(waypoint.StartPoint.Lat, waypoint.EndPoint.Lat);
                            maxWayPointLon = MAX(waypoint.StartPoint.Lon, waypoint.EndPoint.Lon);
                            
                            minWayPointLat = MIN(waypoint.StartPoint.Lat, waypoint.EndPoint.Lat);
                            minWayPointLon = MIN(waypoint.StartPoint.Lon, waypoint.EndPoint.Lon);
                            isFirstWaypoint = false;
                        }//init bounding box
                        
                        NSString *str = [curStep valueForKey:@"html_instructions"];
                        str = [self removeInvalidCharacter:str];
                        waypoint.Description = str;
                        
                       // waypoint.Description = [curStep valueForKey:@"html_instructions"];
                       // NSLog(@"Description is : %@", waypoint.Description);
                        
                        tmp = [curStep objectForKey:@"polyline"];
                        if(tmp!=nil)
                        {
                            waypoint.PointsData = [tmp valueForKey:@"points"];
                        }
                        
                        [seg addwaypoint:waypoint];
                                             
                    }
                    
                                        
                            
                }//process each waypoint
                
                seg.MaxPos.Lat = maxWayPointLat;
                seg.MaxPos.Lon = maxWayPointLon;
                seg.MinPos.Lat = minWayPointLat;
                seg.MinPos.Lon = minWayPointLon; 
//                NSLog(@"LAT IS: %f\n", seg.MaxPos.Lat);
//                NSLog(@"LAT IS: %f\n", maxWayPointLat);

                
                if(isFirstSeg)
                {
                    maxSegLat = seg.MaxPos.Lat;
                    maxSegLon = seg.MaxPos.Lon;
                    
                    minSegLat = seg.MinPos.Lat;
                    minSegLon = seg.MinPos.Lon;
                    isFirstSeg = false;
                }
                else 
                {
                    maxSegLat = MAX(seg.MaxPos.Lat, maxSegLat);
                    maxSegLon = MAX(seg.MaxPos.Lon, maxSegLon);
                    minSegLat = MIN(seg.MaxPos.Lat, minSegLat);
                    minSegLon = MIN(seg.MaxPos.Lon, minSegLon);
                }
                
                [CurRouteData addSegment:seg];
                
            }//process each segment;
            
            CurRouteData.MaxPos.Lat = maxSegLat;
            CurRouteData.MaxPos.Lon = maxSegLon;
            CurRouteData.MinPos.Lat = minSegLat;
            CurRouteData.MinPos.Lon = minSegLon;
            
        }//process each route
        
    }

}

-(NSString *) removeInvalidCharacter:(NSString *) str
{
   // str = [str r:[NSCharacterSet characterSetWithCharactersInString:@"<b>"]];
   // str = [str stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"</b>"]];
//    str = [str stringByReplacingOccurrencesOfString:@"</b>" withString:@""];
 //   str = [str stringByReplacingOccurrencesOfString:@"<b>" withString:@""];
    
    NSError* error = NULL;
    
    NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern:@"<.*?>" options:0 error:&error];
 //   NSString* sample = @"";
 //   NSLog(@"Start:%@",sample);
    str = [regex stringByReplacingMatchesInString:str options:0
                                                         range:NSMakeRange(0, str.length)
                                                  withTemplate:@""];
    return str;
}

-(void) resetRouteData;
{
    if(CurRouteData)
    {
        [CurRouteData dealloc];
    }
    CurRouteData = [[RouteData alloc]init ];
}





@end
